package work.chenbo.springboot.security.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import work.chenbo.springboot.security.config.properties.SecurityProperties;
import work.chenbo.springboot.security.constant.LoginType;
import work.chenbo.springboot.security.model.SimpleResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author ChenBo
 * @className BrowerSecurityController
 * @date 2020/11/5
 */
@RestController
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
@RequiredArgsConstructor
@Slf4j
public class BrowserSecurityController {
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    private RequestCache requestCache = new HttpSessionRequestCache();

    private final SecurityProperties securityProperties;

    @RequestMapping("/authentication/require")
    public SimpleResponse requestAuthentication(HttpServletRequest request, HttpServletResponse response){
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if(Objects.nonNull(savedRequest)){
            String redirectUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转得请求是:{}",redirectUrl);

            if(LoginType.REDIRECT.equals(securityProperties.getLoginType())){
                String loginPage = securityProperties.getLoginPage();
                try {
                    redirectStrategy.sendRedirect(request,response,loginPage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return SimpleResponse.getFail("访问的服务需要身份认证,请求登录");
    }

}
